/**
 Temelia - Parser for performance log file

 Copyright (C) 2008, 2009 Ceata (http://cod.ceata.org/proiecte/temelia).

 @author Dascalu Laurentiu

 This program is free software; you can redistribute it and
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 3
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package org.ceata.temelia;

import java.io.RandomAccessFile;
import java.util.Iterator;
import java.util.LinkedList;

public class TextParser implements Iterator<TestInfo> {
	private LinkedList<TestInfo> testsPool;
	RandomAccessFile fin;

	public TextParser(String inputFile) {
		testsPool = new LinkedList<TestInfo>();
		try {
			fin = new RandomAccessFile(inputFile, "rw");
			readTestInfo();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void readTestInfo() {
		try {
			String line = fin.readLine();

			if (line == null)
				return;

			String dataStructure = line.split("\"")[1];
			String method;
			String library;
			String size;
			String time;
			TestInfo currentTest = null;

			while (true) {
				line = fin.readLine().trim();

				if (line.equals("</data_structure>")) {
					if (currentTest != null)
						testsPool.add(currentTest);

					break;
				}

				if (line.startsWith("<test_case")) {
					if (currentTest != null)
						testsPool.add(currentTest);

					String[] tokens = line.split("\"");
					method = tokens[1];
					library = tokens[3];
					currentTest = new TestInfo();
					currentTest.setDataStructure(dataStructure);
					currentTest.setMethod(method);
					currentTest.setLibrary(library);
				} else if (line.startsWith("<test_unit")) {
					String[] tokens = line.split("\"");
					size = tokens[1];
					time = tokens[3];
					currentTest.addTestCaseData(Double.parseDouble(size),
							Double.parseDouble(time));
				} else if (line.startsWith("</test_case")) {

				} else {
					System.out.println("Inconsistent line: " + line);
					System.exit(1);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean hasNext() {
		return !testsPool.isEmpty();
	}

	@Override
	public TestInfo next() {
		TestInfo test = testsPool.poll();
		readTestInfo();
		return test;
	}

	@Override
	public void remove() {
		// Unsupported
	}
}
